import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:skeletonizer/skeletonizer.dart';
import '../../core/viewmodels/home_viewmodel.dart';
import '../../core/constants/app_constants.dart';
import '../../shared/widgets/error_widget.dart';
import '../../shared/widgets/cached_avatar.dart';
import '../../shared/widgets/skeleton_loader.dart';

class HomeTabPage extends StatefulWidget {
  const HomeTabPage({super.key});

  @override
  State<HomeTabPage> createState() => _HomeTabPageState();
}

class _HomeTabPageState extends State<HomeTabPage> {
  @override
  void initState() {
    super.initState();
    // 延迟加载，确保 token 已保存完成
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      // 等待一小段时间，确保 token 已保存
      await Future.delayed(const Duration(milliseconds: 100));
      if (mounted) {
        context.read<HomeViewModel>().loadRecentContacts();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '聊天',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.w600,
          ),
        ),
        automaticallyImplyLeading: false, // 禁用回退按钮
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              // TODO: 搜索功能
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('搜索功能开发中')),
              );
            },
          ),
        ],
      ),
      body: Consumer<HomeViewModel>(
        builder: (context, viewModel, child) {
          if (viewModel.isLoading && viewModel.recentContacts.isEmpty) {
            return Skeletonizer(
              enabled: true,
              child: ListView.builder(
                padding: const EdgeInsets.symmetric(vertical: 8),
                itemCount: 5,
                itemBuilder: (context, index) => const ListItemSkeleton(),
              ),
            );
          }

          if (viewModel.hasError && viewModel.recentContacts.isEmpty) {
            return AppErrorWidget(
              error: viewModel.errorMessage!,
              onRetry: () {
                viewModel.clearError();
                viewModel.loadRecentContacts();
              },
            );
          }

          if (viewModel.recentContacts.isEmpty) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    padding: const EdgeInsets.all(24),
                    decoration: BoxDecoration(
                      color: Colors.grey[100],
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      Icons.chat_bubble_outline,
                      size: 64,
                      color: Colors.grey[400],
                    ),
                  ),
                  const SizedBox(height: 24),
                  Text(
                    '暂无聊天记录',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.w500,
                      color: Colors.grey[700],
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '去联系人列表添加好友开始聊天吧',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[500],
                    ),
                  ),
                  const SizedBox(height: 32),
                  OutlinedButton.icon(
                    onPressed: () => viewModel.refresh(),
                    icon: const Icon(Icons.refresh, size: 18),
                    label: const Text('刷新'),
                    style: OutlinedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 24,
                        vertical: 12,
                      ),
                    ),
                  ),
                ],
              ),
            );
          }

          return EasyRefresh(
            onRefresh: () async {
              await viewModel.refresh();
            },
            child: ListView.builder(
              padding: const EdgeInsets.symmetric(vertical: 8),
              itemCount: viewModel.recentContacts.length,
              itemBuilder: (context, index) {
                final contact = viewModel.recentContacts[index];
                return Material(
                  color: Colors.transparent,
                  child: InkWell(
                    onTap: () {
                      // 导航到聊天详情页面
                      Navigator.of(context).pushNamed(
                        AppConstants.routeChatDetail,
                        arguments: contact,
                      );
                    },
                    borderRadius: BorderRadius.circular(12),
                    child: Container(
                    margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                    padding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 12,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(
                        color: Colors.grey.shade200,
                        width: 0.5,
                      ),
                    ),
                    child: Row(
                      children: [
                        // 头像
                        CachedAvatar(
                          imageUrl: contact.avatar,
                          name: contact.displayName,
                          size: 56,
                          borderRadius: 28,
                        ),
                        const SizedBox(width: 16),
                        // 内容区域
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Expanded(
                                    child: Text(
                                      contact.displayName,
                                      style: const TextStyle(
                                        fontWeight: FontWeight.w600,
                                        fontSize: 16,
                                        color: Colors.black87,
                                      ),
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                  // 时间（暂时不显示，等有消息数据后再添加）
                                  // Text(
                                  //   _formatTime(lastMessageTime),
                                  //   style: TextStyle(
                                  //     color: Colors.grey[500],
                                  //     fontSize: 12,
                                  //   ),
                                  // ),
                                ],
                              ),
                              const SizedBox(height: 4),
                              Text(
                                contact.username,
                                style: TextStyle(
                                  color: Colors.grey[600],
                                  fontSize: 14,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(width: 8),
                        // 右箭头
                        Icon(
                          Icons.chevron_right,
                          color: Colors.grey[400],
                          size: 20,
                        ),
                      ],
                    ),
                    ),
                  ),
                );
              },
            ),
          );
        },
      ),
    );
  }
}

